#include <cstdio>
#include <vector>
#include <cstring>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

int min( int a, int b ) { return ( a < b ) ?a: b; }

struct Edge
{
    int v, id;
    bool flag;
    Edge( ) { }
    Edge( int _v, int _id, bool _flag )
        : v( _v ), id( _id ), flag( _flag ) { }
};

struct Node
{
    int u, v, id;
    Node( ) { }
    Node( int _u, int _v, int _id )
        : u( _u ), v( _v ), id( _id ) { }
};

bool operator < ( const Node &a, const Node &b )
{
    return a.id < b.id;
}

vector<Node> aa;
vector<Edge> li[ 10001 ];
int n, m, dfn[ 10001 ], low[ 10001 ], cnt;
bool visit[ 10001 ];
char s[ 10001 ][ 20 ];
map<string, int> mp;

void init( )
{
    int i, u, v, t = 1;
    char na[ 20 ];
    string ts;
    scanf("%d%d", &n, &m);
    mp.clear( );
    for ( i = 0; i < n; i++ )
        li[ i ].clear( );
    for ( i = 0; i < m; i++ )
    {
        scanf("%s", na);
        ts = na;
        if ( !mp[ ts ] )
        {
            strcpy( s[ t - 1 ], na );
            mp[ ts ] = t++;
        }
        u = mp[ ts ] - 1;
        scanf("%s", na);
        ts = na;
        if ( !mp[ ts ] )
        {
            strcpy( s[ t - 1 ], na );
            mp[ ts ] = t++;
        }
        v = mp[ ts ] - 1;
        li[ u ].push_back( Edge( v, i, 1 ) );
        li[ v ].push_back( Edge( u, i, 0 ) );
    }
    memset( visit, 0, sizeof( visit ) );
    cnt = 0;
    aa.clear( );
}

void dfs( int p, int fa )
{
    int i;
    dfn[ p ] = low[ p ] = cnt++;
    visit[ p ] = 1;
    for ( i = 0; i < li[ p ].size( ); i++ )
    {
        if ( li[ p ][ i ].v == fa ) continue;
        if ( !visit[ li[ p ][ i ].v ] )
        {
            dfs( li[ p ][ i ].v, p );
            low[ p ] = min( low[ li[ p ][ i ].v ], low[ p ] );
            if ( low[ li[ p ][ i ].v ] > dfn[ p ] )
                if ( li[ p ][ i ].flag )
                    aa.push_back( Node( p, li[ p ][ i ].v, li[ p ][ i ].id ) );
                else
                    aa.push_back( Node( li[ p ][ i ].v, p, li[ p ][ i ].id ) );
        }
        else
            low[ p ] = min( low[ p ], dfn[ li[ p ][ i ].v ] );
    }
}

void work( )
{
    int i;
    bool flag = false;
    for ( i = 0; i < n; i++ )
        if ( !visit[ i ] )
        {
            if ( flag )
            {
                puts("0");
                return ;
            }
            flag = true;
            dfs( i, -1 );
        }
    sort( aa.begin( ), aa.end( ) );
    printf("%d\n", aa.size( ));
    for ( i = 0; i < aa.size( ); i++ )
        printf("%s %s\n", s[ aa[ i ].u ], s[ aa[ i ].v ]);
}

int main( )
{
    int t;
    scanf("%d", &t);
    while ( t-- )
    {
        init( );
        work( );
    }
    return 0;
}
